from common.exchange_mail_util import ExchangeUtil
import subprocess
from common.logger import Logger
from datetime import datetime
from dataflow.conf import notify_emails

logger = Logger("check_process.log").getLogger()
#crontab * * * * * python3 /home/lirui/projects/bigdata_imei/dataflow/check_process.py

logger.info('start ' + str(datetime.now()))
(status, output) = subprocess.getstatusoutput('curl -s http://txt.go.sohu.com/ip/soip |  grep -P -o -i "(\d+\.\d+.\d+.\d+)"')
ip = ''
if status == 0:
    ip = output

content = ''

cmd = 'ps aux|grep uwsgi| grep -v grep | wc -l'
uwsgi_cnt = 5
nginx_cnt = 5

(status, output) = subprocess.getstatusoutput(cmd)
if status == 0:
    if int(output) < uwsgi_cnt:
        content += ' uwsgi process count error ' + str(output) + ' '

        (status, output) = subprocess.getstatusoutput('ps aux|grep uwsgi')
        content += output

        if int(output) > 0:
            cmd = ''' ps aux|grep uwsgi| grep -v grep | awk -F ' ' '{print $2}'|xargs kill -9 '''
            (status, output) = subprocess.getstatusoutput(cmd)
            if status != 0:
                content += ' kill uwsgi fail '

        cmd = ''' ps aux|grep nginx| grep -v grep | awk -F ' ' '{print $2}'|xargs kill -9 '''
        (status, output) = subprocess.getstatusoutput(cmd)
        if status != 0:
            content += ' kill nginx fail '

        cmd = ''' nohup uwsgi --ini /home/lirui/projects/bigdata_imei/server_conf/uwsgi.ini & '''
        (status, output) = subprocess.getstatusoutput(cmd)
        if status != 0:
            content += ' restart uwsgi fail '

        cmd = ''' nginx -c /usr/local/nginx/conf/nginx.conf '''
        (status, output) = subprocess.getstatusoutput(cmd)
        if status != 0:
            content += ' restart nginx fail '

else:
    content += ' wc -l uwsgi fail '

cmd = 'ps aux|grep nginx| grep -v grep | wc -l'
(status, output) = subprocess.getstatusoutput(cmd)
if status == 0:
    if int(output) < nginx_cnt:
        content += ' nginx process count error ' + str(output) + ' '

        (status, output) = subprocess.getstatusoutput('ps aux|grep nginx')
        content += output

        cmd = ''' ps aux|grep nginx| grep -v grep | awk -F ' ' '{print $2}'|xargs kill -9 '''
        (status, output) = subprocess.getstatusoutput(cmd)
        if status != 0:
            content += ' kill nginx fail '

        cmd = ''' nginx -c /usr/local/nginx/conf/nginx.conf '''
        (status, output) = subprocess.getstatusoutput(cmd)
        if status != 0:
            content += ' restart nginx fail '

else:
    content += ' wc -l nginx fail '


if content != '':
    mail = ExchangeUtil('输入法服务异常', notify_emails)
    mail.set_content(ip + '\n' + content)
    mail.send()
    logger.info(content)

logger.info('end ' + str(datetime.now()))
